package com.huluobo.base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2024/9/18.
 */
abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    protected val binding: VDB by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null, layoutInflater) as VDB
    }

    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.i("TagA", "t:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this, ::Error)
        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()

    fun getTime(): String {
        val time = System.currentTimeMillis()
        var tampTime = TimeUtils.millis2String(time, SimpleDateFormat("yyyy-MM-dd"))
        tampTime += "T"
        tampTime += TimeUtils.millis2String(time, SimpleDateFormat("hh:mm:ss"))
        tampTime += "Z"
        return tampTime
    }
}